<template>
  <div>
    <!-- <warning-bar title="注：右上角头像下拉可切换角色" /> -->
    <div class="gva-table-box">
      <div>
        <el-form :inline="true" :model="searchInfo">
          <el-form-item label="账号">
            <el-input v-model.trim="searchInfo.account" placeholder="搜索条件"/>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model.trim="searchInfo.phone" placeholder="搜索条件"/>
          </el-form-item>
          <el-form-item label="所属团队">
            <el-select v-model="searchInfo.teamId" label="父级菜单" filterable placeholder="请选择" @change="onSubmit">
              <el-option label="查询所有" value=""/>
              <el-option v-for="item in teamOptions" :key="item.teamId" :label="item.teamName" :value="item.teamId"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUser">新增用户</el-button>
      </div>
      <el-table :data="tableData" v-loading="loading" row-key="ID">
        <el-table-column align="left" label="账号" min-width="120" prop="account"/>
        <el-table-column align="left" label="姓名" min-width="120" prop="name"/>
        <el-table-column align="left" label="手机号" min-width="160" prop="phone"/>
        <el-table-column align="left" label="性别" min-width="70" prop="sex"/>
        <el-table-column align="left" label="所属团队" min-width="150">
          <template #default="scope">
            <el-cascader v-model="scope.row.teamId" :options="teamOptions" :show-all-levels="false" collapse-tags
                         :props="{ checkStrictly: true, label: 'teamName', value: 'teamId', disabled: 'disabled', emitPath: false }"
                         :clearable="false" @visible-change="(flag) => { changeTeam(scope.row, flag) }"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="用户角色" min-width="180">
          <template #default="scope">
            <el-cascader v-model="scope.row.roleId" :options="authOptions" :show-all-levels="false" collapse-tags
                         :props="{ checkStrictly: true, label: 'roleName', value: 'roleId', disabled: 'disabled', emitPath: false }"
                         :clearable="false" @visible-change="(flag) => { changeAuthority(scope.row, flag) }"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="启用" min-width="90">
          <template #default="scope">
            <el-switch v-model="scope.row.status" inline-prompt :active-value="0" :inactive-value="1"
                       @change="() => { switchEnable(scope.row) }"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="openEdit(scope.row)">编辑</el-button>
            <el-popover v-model="scope.row.visible" placement="top" width="160">
              <p>确定要删除吗?</p>
              <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="scope.row.visible = false">取消</el-button>
                <el-button type="primary" @click="deleteUserFunc(scope.row)">确定</el-button>
              </div>
              <template #reference>
                <el-button type="danger" link icon="delete">删除</el-button>
              </template>
            </el-popover>
            <el-button type="warning" link icon="magic-stick" @click="resetPasswordFunc(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="pageSize"
                       :page-sizes="[10, 30, 50, 100]" :total="total"
                       layout="total, sizes, prev, pager, next, jumper"
                       :hide-on-single-page="pageSize===10"
                       @current-change="handleCurrentChange" @size-change="handleSizeChange"/>
      </div>
    </div>
    <!--新增修改模态框-->
    <el-dialog v-model="addUserDialog" :title="dialogFlag==='add'?'新增用户':'修改用户'" :show-close="false"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
      <div style="height:40vh;overflow:auto;padding:0 12px;">
        <el-form ref="userForm" :rules="rules" :model="userInfo" label-width="80px">
          <el-form-item v-if="dialogFlag === 'add'" label="账号" prop="userName">
            <el-input v-model.trim="userInfo.account"/>
          </el-form-item>
          <el-form-item v-if="dialogFlag === 'edit'" label="账号" prop="userName">
            <el-input v-model.trim="userInfo.account" readonly="readonly"/>
          </el-form-item>
          <el-form-item v-if="dialogFlag === 'add'" label="密码" prop="password">
            默认密码为123456
          </el-form-item>
          <el-form-item label="昵称" prop="name">
            <el-input v-model.trim="userInfo.name"/>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model.trim="userInfo.phone"/>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model.trim="userInfo.sex" class="ml-4">
              <el-radio label="男" size="large">男</el-radio>
              <el-radio label="女" size="large">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所属团队">
            <el-select v-model="userInfo.teamId" filterable placeholder="请选择">
              <el-option v-for="item in teamOptions" :key="item.teamId" :label="item.teamName" :value="item.teamId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="用户角色" prop="roleId">
            <el-cascader v-model="userInfo.roleId" style="width:100%" :options="authOptions" :show-all-levels="false"
                         :props="{ checkStrictly: true, label: 'roleName', value: 'roleId', disabled: 'disabled', emitPath: false }"
                         :clearable="false"/>
          </el-form-item>
          <el-form-item label="启用" prop="disabled">
            <el-switch v-model="userInfo.status" inline-prompt :active-value="0" :inactive-value="1"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddUserDialog">取 消</el-button>
          <el-button type="primary" @click="enterAddUserDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>

import {
  getUserList,
  setUserAuthorities,
  save,
  deleteUser, setUserTeam
} from '@/api/user'

import {getAuthorityList} from '@/api/authority'
import {setUserInfo, resetPassword} from '@/api/user.js'

import {nextTick, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getTeamList} from "@/api/team";

defineOptions({
  name: 'User',
})

// const path = ref(import.meta.env.VITE_BASE_API + '/')
// 初始化相关

const loading = ref(true)
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({
  phone: '',
  account: '',
  teamId: ''
})
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  loading.value = true
  const table = await getUserList({page: page.value, pageSize: pageSize.value, ...searchInfo.value})
  if (table.code === 0) {
    tableData.value = table.data.records
    total.value = +table.data.total
    loading.value = false
  }
}

//初始化
const initPage = async () => {
  const auths = await getAuthorityList({page: 1, pageSize: 999})
  const teams = await getTeamList({page: 1, pageSize: 999})
  setAuthOptions(auths.data.records)
  setTeamOptions(teams.data.records)
  await getTableData()
}


const resetPasswordFunc = (row) => {
  ElMessageBox.confirm(
      '是否将此用户密码重置为123456?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await resetPassword({userId: row.userId})
    ElMessage({type: res.code === 0 ? 'success' : 'error', message: res.msg})
  })
}

//获取角色
const authOptions = ref([])
const setAuthOptions = (authData) => {
  authOptions.value = authData
}

//获取团队
const teamOptions = ref([])
const setTeamOptions = (teamData) => {
  teamOptions.value = teamData
}


const deleteUserFunc = async (row) => {
  const res = await deleteUser(row.userId)
  if (res.code === 0) {
    ElMessage.success(res.msg)
    row.visible = false
    await getTableData()
  }
}

// 弹窗相关
const userInfo = ref({
  userId: 0,
  account: '',
  name: '',
  sex: '',
  roleId: '',
  teamId: '',
  phone: '',
  status: 1,
})

const rules = ref({
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 5, message: '最低5位字符', trigger: 'blur'}
  ],

  name: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  phone: [
    {pattern: /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/, message: '请输入合法手机号', trigger: 'blur'},
  ],
  roleId: [
    {required: true, message: '请选择用户角色', trigger: 'blur'}
  ]
})
const userForm = ref(null)
const enterAddUserDialog = async () => {
  userForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...userInfo.value
      }
      if (dialogFlag.value === 'add') {
        const res = await save(req)
        if (res.code === 0) {
          ElMessage({type: 'success', message: res.msg})
          await getTableData()
          closeAddUserDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await setUserInfo(req)
        if (res.code === 0) {
          ElMessage({type: 'success', message: res.msg})
          await getTableData()
          closeAddUserDialog()
        }
      }
    }
  })
}

const addUserDialog = ref(false)
const closeAddUserDialog = () => {
  userForm.value.resetFields()
  initForm()
  addUserDialog.value = false
}

const dialogFlag = ref('add')

const addUser = () => {
  dialogFlag.value = 'add'
  initForm()
  addUserDialog.value = true
}

const changeAuthority = async (row, flag) => {
  if (row.roleId === null || flag) {
    return
  }
  await nextTick()
  const res = await setUserAuthorities({
    userId: row.userId,
    roleId: row.roleId
  })
  if (res.code === 0) {
    ElMessage({type: 'success', message: res.msg})
  }
}
const changeTeam = async (row, flag) => {
  if (row.teamId === null || flag) {
    return
  }
  await nextTick()
  const res = await setUserTeam({
    userId: row.userId,
    teamId: row.teamId
  })
  if (res.code === 0) {
    ElMessage({type: 'success', message: res.msg})
  }
}


const initForm = () => {
  if (userForm.value) {
    userForm.value.resetFields()
  }
  userInfo.value = {
    userId: 0,
    account: '',
    name: '',
    sex: '',
    roleId: '',
    phone: '',
    status: 1,
  }
}

const openEdit = (row) => {
  dialogFlag.value = 'edit'
  userInfo.value = JSON.parse(JSON.stringify(row))
  addUserDialog.value = true
}

const switchEnable = async (row) => {
  userInfo.value = JSON.parse(JSON.stringify(row))
  await nextTick()
  const req = {
    ...userInfo.value
  }
  const res = await setUserInfo(req)
  if (res.code === 0) {
    ElMessage({type: 'success', message: `${req.status === 1 ? '禁用' : '启用'}成功`})
    await getTableData()
  }
}
const onSubmit = () => {
  getTableData()
}
const onReset = () => {
  searchInfo.value = {
    phone: '',
    account: '',
    teamId: ''
  }
  getTableData()
}


initPage()

</script>
<style lang="scss">
.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}
</style>
